import history from 'history/browser';
import { action, computed, makeObservable, observable, ObservableMap } from 'mobx';
import RootStore, { IGlobalStore } from 'store/RootStore';

type PrivateFields = '_params' | '_hash';

export default class LocationStore implements IGlobalStore {
    readonly _params: ObservableMap<string, string> = new ObservableMap();
    private _hash = '';
    private _search = '';
    private _code = '';

    constructor() {
        makeObservable<LocationStore, PrivateFields>(this, {
            _params: observable.ref,
            _hash: observable,
            hash: computed,
            getSearchParams: action.bound,
            setHash: action.bound,
            setSearch: action.bound,
        });
    }

    get hash(): string {
        return this._hash;
    }

    getSearchParams(key: string): string | undefined {
        return this._params.get(key);
    }

    setSearch(search: string): void {
        if (this._search !== search) {
            this._search = search;
            new URLSearchParams(search).forEach((value, key) => {
                this._params.set(key, value);
            });
            const code = this._params.get('code');

            if (code && this._code !== code) {
                this._code = code;
                this._params.delete('code');
                const reg = new RegExp(`[?&]*code=${code}`);
                history.replace(window.location.href.replace(reg, ''));
                RootStore.githubOAuth.githubAuthorize(code);
            }
        }
    }

    setHash(hash: string): void {
        if (this._hash !== hash) {
            this._hash = hash;
        }
    }

    destroy(): void {
        return;
    }
}
